var app = getApp();
Page({
  data: {
    hidden: true,            //加载提示
    msg: '摇一摇，选个菜',
    foodId: '',
    foodBook: {
      name:'摇一摇，有惊喜'
    },
    ingredientsArray:[],
    stepArray:[],

    lastTime : 0,
    x : 0,
    y : 0,
    z : 0,
    lastX : 0,
    lastY : 0,
    lastZ : 0,
    shakeSpeed : 110
  },
  isShow:false,             //是否显示（如果有tab，则所有页面都有监听，通过此来判断在不显示的页面是否执行摇一摇效果）
  isReading:false,          //是否在执行
  //摇一摇方法
  shake:function (acceleration) {
    var that = this;
    //如果不是当前页，不执行
    if(!that.isShow){
        return;
    }
    if(that.isReading){
        return;
    }
    var nowTime = new Date().getTime(); //记录当前时间
    //如果这次摇的时间距离上次摇的时间有一定间隔 才执行
    if (nowTime - that.data.lastTime > 100) {
      var diffTime = nowTime - that.data.lastTime; //记录时间段
      that.setData({
        lastTime: nowTime,
        x : acceleration.x, //获取x轴数值，x轴为垂直于北轴，向东为正
        y : acceleration.y, //获取y轴数值，y轴向正北为正
        z : acceleration.z //获取z轴数值，z轴垂直于地面，向上为正
      });
      //计算 公式的意思是 单位时间内运动的路程，即为我们想要的速度
      var speed = Math.abs(acceleration.x + acceleration.y + acceleration.z - that.data.lastX - that.data.lastY - that.data.lastZ) / diffTime * 10000;
      if (speed > that.data.shakeSpeed) { //如果计算出来的速度超过了阈值，那么就算作用户成功摇一摇
        console.log('关闭监听');
        wx.stopAccelerometer();
        that.setData({
          hasInit: false,
          canvas: {}
        })
        that.audioCtx.setSrc('http://123.207.0.183/application/images/s.mp3')
        that.audioCtx.play()
        // wx.showLoading({
        //   title: '选菜中...'
        // })
        that.setData({
          hidden: true,
          msg: '选菜中...'
        });
        //随即一个菜谱
        that.getOneFood();
      }
      that.setData({
        lastX: acceleration.x, //获取x轴数值，x轴为垂直于北轴，向东为正
        lastY: acceleration.y, //获取y轴数值，y轴向正北为正
        lastZ: acceleration.z //获取z轴数值，z轴垂直于地面，向上为正
      });
    }
  },

  
  onShow: function () {
    console.log('开始=====');
    var that = this;
    this.isShow = true;
    //创建音频
    that.audioCtx = wx.createAudioContext('myAudio')
    //开始监听
    console.log('开始监听');
    wx.startAccelerometer();
    wx.onAccelerometerChange(that.shake);

  },
  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
    
  },
  
  //随机一个菜谱
  getOneFood:function(){
    var that = this;
    if(that.isReading){
      return;
    }
    that.isReading = true;
    that.setData({
      hidden: false
    })
    wx.request({
      url: 'https://mouthwar.com/mouthwar/api/food/book/getfoodbook/random',
      data: {
        
      },
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        var data = res.data;//接口返回的数据
        console.log("新闻详细数据==" + data);
        //赋值
        var code = data.code;
        if (code == 100200) {
          var resData = data.data;
          var ingredients = JSON.parse(resData.ingredients); 
          var step = JSON.parse(resData.step); 
          //赋值
          that.setData({
            foodBook: resData,
            ingredientsArray: ingredients,
            stepArray: step
          })

          setTimeout(function () {
            that.setData({
              hidden: true
            });
          }, 300);
        };
      },
      fail: function (res) {
        console.log("接口调用失败=" + res);
        that.setData({
          msg: res.errMsg
        });
      },
      complete:function(){
          //再次重置
          console.log('再开始监听');
          that.isReading = false;
          wx.startAccelerometer();
      }
    })
  },
  onShareAppMessage: function (res) {
    var that = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    var pathurl = '/pages/yaoyiyao/yaoyiyao';
    var titleStr = '不知道吃什么？来摇菜！';
    if(that.data.foodBook.id!=null
      ||that.data.foodBook.id!=undefined
      ||that.data.foodBook.id!=''){
      pathurl = '/pages/food/info/food_info?id='+that.data.foodBook.id;
      titleStr = '哈哈，摇到了一道满意的菜';
    }
    return {
      title: titleStr,
      path: pathurl,
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  }
})